﻿/*========================== 
 * @author 郑金泉
 * @desc SQL BETWEEN 条件类
 * ========================= */
using System;
using System.Collections.Generic;
using System.Text;

using Obsidian.Edm;

namespace Obsidian.Data.Sql
{
    public class BetweenCondition : SqlCondition, ISqlCondition
    {

        private ModelField _modelField;
        private object _startValue = null;
        private object _endValue = null;

        public BetweenCondition(ModelField field, object startVal, object endVal)
        {
            this.Init(Sql.LogicalOperator.AND, field, startVal, endVal);
        }

        public BetweenCondition(LogicalOperator logicalOperator, ModelField field, object startVal, object endVal)
        {
            this.Init(logicalOperator, field, startVal, endVal);
        }

        private void Init(LogicalOperator logicalOperator, ModelField field, object startVal, object endVal)
        {
            this.LogicalOperator = logicalOperator;
            this._modelField = field;
            this._startValue = startVal;
            this._endValue = endVal;
        }

        public string BuildSqlText()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(this._modelField.GetDbField().TablePrefixName)
                .Append(" BETWEEN ");

            FieldType type = this._modelField.Type;
            DataBaseType dbType = this._modelField.Model.GetDataBase().Type;
            string startVal = DbHandler.Escape(dbType, this._startValue.ToString());
            string endVal = DbHandler.Escape(dbType, this._endValue.ToString());

            if (type == FieldType.String || type == FieldType.DateTime)
            {
                sb.Append("'").Append(startVal).Append("' AND '")
                    .Append(endVal).Append("' ");
            }
            else
            {
                sb.Append(startVal).Append(" AND ")
                    .Append(endVal).Append(" ");
            }
            return sb.ToString();
        }

    }

}
